import { useCallback } from 'react'
import { useProjectStore } from '@/store/projectStore'
import { Project, CreateProjectParams } from '@/types/project'

// 自定义钩子，简化项目状态的访问
export const useProjects = () => {
  // 获取状态
  const {
    projects,
    currentProject,
    isLoading,
    error,
    fetchProjects,
    createProject,
    updateProject,
    deleteProject,
    selectProject
  } = useProjectStore()
  
  // 获取按更新时间排序的项目
  const sortedProjects = projects
    .slice()
    .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime())
  
  // 按状态过滤项目
  const getProjectsByStatus = useCallback((status: Project['status']) => {
    return projects.filter(project => project.status === status)
  }, [projects])
  
  // 按标签过滤项目
  const getProjectsByTag = useCallback((tag: string) => {
    return projects.filter(project => project.tags.includes(tag))
  }, [projects])
  
  // 创建项目并选择它
  const createAndSelectProject = useCallback(async (params: CreateProjectParams) => {
    const newProject = await createProject(params)
    selectProject(newProject.id)
    return newProject
  }, [createProject, selectProject])
  
  // 提取所有标签
  const getAllTags = useCallback(() => {
    const tagsSet = new Set<string>()
    projects.forEach(project => {
      project.tags.forEach(tag => tagsSet.add(tag))
    })
    return Array.from(tagsSet)
  }, [projects])
  
  // 搜索项目
  const searchProjects = useCallback((query: string) => {
    if (!query) return projects
    
    const lowerQuery = query.toLowerCase()
    return projects.filter(project => 
      project.title.toLowerCase().includes(lowerQuery) ||
      project.description.toLowerCase().includes(lowerQuery) ||
      project.tags.some(tag => tag.toLowerCase().includes(lowerQuery))
    )
  }, [projects])
  
  return {
    // 状态
    projects,
    sortedProjects,
    currentProject,
    isLoading,
    error,
    
    // 基础操作
    fetchProjects,
    createProject,
    updateProject,
    deleteProject,
    selectProject,
    
    // 高级操作
    getProjectsByStatus,
    getProjectsByTag,
    createAndSelectProject,
    getAllTags,
    searchProjects
  }
} 